package com.openlogic.logic.listener;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.noear.solon.annotation.Inject;
import org.noear.solon.cloud.CloudEventHandler;
import org.noear.solon.cloud.annotation.CloudEvent;
import org.noear.solon.cloud.model.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSON;
import com.mybatisflex.core.query.QueryWrapper;
import com.openlogic.common.core.constants.CacheConstant;
import com.openlogic.common.redis.service.RedisService;
import com.openlogic.datasource.api.entity.DataColumnEntity;
import com.openlogic.datasource.api.entity.DataSourceEntity;
import com.openlogic.datasource.api.entity.DataTableEntity;
import com.openlogic.datasource.api.event.DataCacheEventModel;
import com.openlogic.logic.mapper.datasource.DataColumnMapper;
import com.openlogic.logic.mapper.datasource.DataSourceMapper;
import com.openlogic.logic.mapper.datasource.DataTableMapper;

/**
 * @ClassName: CacheMetaDataEventListener
 * @Description: 元数据缓存事件监听
 * @author weiyongpeng
 * @date 2024年11月10日 下午6:15:52
 */
//用代理模式订阅（。实体已申明主题相关信息）
@CloudEvent(topic = "data.cache.event", group = "cache")
public class DataCacheEventListener implements CloudEventHandler {

	private static final Logger logger = LoggerFactory.getLogger(DataCacheEventListener.class);

	@Inject
	private RedisService redisService;

	@Inject
	private DataSourceMapper dataSourceMapper;

	@Inject
	private DataTableMapper metadataTableDao;

	@Inject
	private DataColumnMapper metadataColumnDao;

	@Override
	public boolean handle(Event event) throws Throwable {
		DataCacheEventModel dataCacheEventModel = JSON.parseObject(event.content(),DataCacheEventModel.class);
		if (StringUtils.equals(dataCacheEventModel.getKey(), CacheConstant.METADATA_SOURCE_KEY)) {
			Boolean hasSourceKey = redisService.hasKey(dataCacheEventModel.getKey());
	        if (hasSourceKey) {
	            redisService.deleteObject(dataCacheEventModel.getKey());
	        }
	        List<DataSourceEntity> sourceEntityList = dataSourceMapper.selectListByQuery(QueryWrapper.create());
	        if (CollectionUtils.isNotEmpty(sourceEntityList)) {
	        	redisService.setCacheList(dataCacheEventModel.getKey(), sourceEntityList);
			}
		} else if(StringUtils.equals(dataCacheEventModel.getKey(), CacheConstant.METADATA_TABLE_KEY)) {
			Boolean hasTableKey = redisService.hasKey(dataCacheEventModel.getKey());
	        if (hasTableKey) {
	            redisService.deleteObject(dataCacheEventModel.getKey());
	        }
	        List<DataTableEntity> tableEntityList = metadataTableDao.selectListByQuery(QueryWrapper.create());
	        if (CollectionUtils.isNotEmpty(tableEntityList)) {
	        	Map<String, List<DataTableEntity>> tableListMap = tableEntityList.stream().collect(Collectors.groupingBy(DataTableEntity::getSourceId));
	        	redisService.setCacheMap(dataCacheEventModel.getKey(), tableListMap);
			}
		} else if(StringUtils.equals(dataCacheEventModel.getKey(), CacheConstant.METADATA_COLUMN_KEY)) {
			Boolean hasColumnKey = redisService.hasKey(dataCacheEventModel.getKey());
	        if (hasColumnKey) {
	            redisService.deleteObject(dataCacheEventModel.getKey());
	        }
	        List<DataColumnEntity> columnEntityList = metadataColumnDao.selectListByQuery(QueryWrapper.create());
	        if (CollectionUtils.isNotEmpty(columnEntityList)) {
	        	Map<String, List<DataColumnEntity>> columnListMap = columnEntityList.stream().collect(Collectors.groupingBy(DataColumnEntity::getTableId));
	        	redisService.setCacheMap(dataCacheEventModel.getKey(), columnListMap);
			}
		}
		logger.info("<<<<<事件处理完毕，缓存成功>>>>>");
		return true;
	}

}
